package com.woniuxy.hotel.user.service.serviceimpl;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.woniuxy.hotel.user.mapper.UserMapper;
import com.woniuxy.hotel.user.pojo.User;
import com.woniuxy.hotel.user.service.UserService;
import com.woniuxy.hotel.util.sendSMS.SDKTestSendTemplateSMS;

@Scope("prototype")
@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RedisTemplate<Object,Object> redisTemplate;

	@Override
	public String findAccountByPhone(String phone) {
		return userMapper.findAccountByPhone(phone);
	}

	@Override
	public User findUserByAccount(String account) {
		return userMapper.findUserByAccount(account);
	}

	@Override
	public User selectByPrimaryKey(int id) {
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public User findUserByPhone(String phone) {
		return userMapper.findUserByPhone(phone);
	}

	@Override
	public void updatePhone(String currentPhone, String newPhone) {
		User user=userMapper.findUserByPhone(newPhone);
		if(user!=null){
			throw new RuntimeException("新手机号已存在");
		}else{
			int result=userMapper.updatePhone(currentPhone,newPhone);
			if(result==0){
				throw new RuntimeException("找不到原手机号码的用户");
			}
		}
	}

	@Override
	public Collection<String> showUserRoles(String account) {
		Collection<String> roles=userMapper.showUserRoles(account);
		return roles;
	}

	@Override
	public String rsPassword(String account, String code, String password) {
		String accode=(String) redisTemplate.opsForValue().get(account);
		if(!accode.equals(code)){
			return "验证码错误";
		}
		String newPassword = new SimpleHash("MD5",password, account,  1024).toString(); //生成的密文
		int result=userMapper.updatePasswordByAccount(account, newPassword);
		if(result==1){
			return "修改成功";
		}else{
			return "修改失败";
		}
	}

	@Override
	public String getLoginSMS(String phone) {
		User user=userMapper.findUserByPhone(phone);
		if(user==null){
			throw new RuntimeException("手机号不存在");
		}else{
			String code=SDKTestSendTemplateSMS.getCode();
			System.out.println(code);
			boolean flag = redisTemplate.hasKey(phone);
	        if (flag) {
	        	throw new RuntimeException("验证码发送失败");
	        }
	        redisTemplate.opsForValue().set(phone, code, 60, TimeUnit.SECONDS);
	       // String result=(String) SDKTestSendTemplateSMS.sendSMS(code, phone);
	       // if(!result.equals("000000")){
	       //	throw new RuntimeException("验证码发送失败");
	       // }
	        return "验证码发送成功！";
		}
	}

	@Override
	public String loginByPhone(String phone, String code) {
		String accode=(String) redisTemplate.opsForValue().get(phone);
		if(!accode.equals(code)){
			throw new RuntimeException("验证码错误");
		}
		User user=userMapper.findUserByPhone(phone);
		user.setPassword("");
		return login(user);
/*		Subject currentUser = SecurityUtils.getSubject();
		if((String)currentUser.getPrincipal()!=null){
			if(!((String)currentUser.getPrincipal()).equals(user.getAccount())){
				currentUser.logout();
			}
		}
		// 2.判断当前用户是否已经认证过
		if (!currentUser.isAuthenticated()) {
			UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), "");
			try {
				currentUser.login(token);// 进行认证
				if(currentUser.hasRole("customer")){
					return "redirect:/Rgx/hotel.html";
				}else{
					return "redirect:/index.html";
				}
			} catch (UnknownAccountException e) {
				throw new UnknownAccountException("用户不存在");
			} catch (IncorrectCredentialsException e) {
				throw new IncorrectCredentialsException("密码错误");
			} catch (LockedAccountException e) {
				throw new LockedAccountException("用户被锁定");
			} catch (AuthenticationException e) {
				e.printStackTrace();
				throw new AuthenticationException("发生很奇怪的事情");
			}
		}else {
			if(currentUser.hasRole("customer")){
				return "redirect:/Rgx/hotel.html";
			}else{
				return "redirect:/index.html";
			}
		}*/
	}

	/**
	 * 处理登录相关逻辑
	 * @param user
	 * @return
	 */
	@Override
	public String login(User user) {
		Subject currentUser = SecurityUtils.getSubject();
		if((String)currentUser.getPrincipal()!=null){
			if(!((String)currentUser.getPrincipal()).equals(user.getAccount())){
				currentUser.logout();
			}
		}
		// 2.判断当前用户是否已经认证过
		if (!currentUser.isAuthenticated()) {
			UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), user.getPassword());
			try {
				currentUser.login(token);// 进行认证
				if(currentUser.hasRole("customer")){
					return "redirect:/Rgx/hotel.html";
				}else{
					return "redirect:/index.html";
				}
			} catch (UnknownAccountException e) {
				throw new UnknownAccountException("用户不存在");
			} catch (IncorrectCredentialsException e) {
				throw new IncorrectCredentialsException("密码错误");
			} catch (LockedAccountException e) {
				throw new LockedAccountException("用户被锁定");
			} catch (AuthenticationException e) {
				e.printStackTrace();
				throw new AuthenticationException("发生很奇怪的事情");
			}
		}else {
			if(currentUser.hasRole("customer")){
				return "redirect:/Rgx/hotel.html";
			}else{
				return "redirect:/index.html";
			}
		}
	}
}
